import {
	IMPickupView2Ability,
	IMPickupView2Controller,
	IMPickupView2ControllerParams,
	IMPickupView2Store,
	INavigateParam,
	IParam,
	IPickupViewPanelAbility,
	ITreeExpBarAbility,
	IViewActionResult,
	MPickupView2ActionType,
} from '@/core/interface';
import { PickupViewController } from './pickup-view-controller';

/**
 * 多项选择视图2控制器
 *
 * @export
 * @class MPickupView2Controller
 * @extends {(DEViewController<T | PickupViewActionType, IPickupViewStore, IPickupViewAbility>)}
 * @template T
 */
export class MPickupView2Controller
	extends PickupViewController<
		MPickupView2ActionType,
		IMPickupView2Store,
		IMPickupView2Ability
	>
	implements IMPickupView2Controller<IMPickupView2Store, IMPickupView2Ability>
{
	/**
	 * 处理视图初始化
	 *
	 * @protected
	 * @param {IMPickupView2ControllerParams<MPickupViewActionType,IMPickupViewAbility>} params
	 * @memberof MPickupView2Controller
	 */
	protected processViewInit(
		params: IMPickupView2ControllerParams<
			MPickupView2ActionType,
			IMPickupView2Ability
		>
	) {
		super.processViewInit(params);
		Object.assign(this.store, {
			selections: [],
			tempSelections: [],
			panelSelectedKeys: [],
			selectionCache: [],
		});
	}

	/**
	 * 树导航栏部件行为
	 *
	 * @protected
	 * @return {*}  {(ITreeExpBarAbility | undefined)}
	 * @memberof MPickupView2Controller
	 */
	protected getTreeExpCtrlAbility(): ITreeExpBarAbility | undefined {
		const expbar = this.model.ctrls.find(
			(ctrl: IParam) => ctrl.controlType === 'TREEEXPBAR'
		);
		return expbar
			? this.getSubAbility<ITreeExpBarAbility>(expbar.name)
			: undefined;
	}

	/**
	 * 按钮行为
	 *
	 * @private
	 * @type {string}
	 * @memberof MPickupView2Controller
	 */
	private buttonAction = '';

	/**
	 * 是否默认选中
	 *
	 * @private
	 * @type {boolean}
	 * @memberof MPickupView2Controller
	 */
	private isDefaultSelect = true;

	/**
	 * 视图挂载
	 *
	 * @param {IParam} [opts={}]
	 * @return {*}  {void}
	 * @memberof MPickupView2Controller
	 */
	public viewMounted(opts: IParam = {}): void {
		super.viewMounted(opts);
		if (this.model.useDefaultLayout) {
			if (!this.isLoadDefault) {
				this.isLoadDefault = true;
				return;
			}
			this.load(opts);
		} else {
			this.initLayout().then(() => {
				if (!this.isLoadDefault) {
					this.isLoadDefault = true;
					return;
				}
				this.load(opts);
			});
		}
	}

	/**
	 * 视图加载
	 *
	 * @param {IParam} [args]
	 * @return {*}  {Promise<IViewActionResult>}
	 * @memberof MPickupView2Controller
	 */
	public load(args?: IParam): Promise<IViewActionResult> {
		const expCtrl = this.getTreeExpCtrlAbility();
		if (expCtrl) {
			this.computeDefaultSelect();
			return expCtrl.load();
		} else {
			return Promise.reject({
				ok: false,
				data: null,
				rowData: { status: 500 },
			});
		}
	}

	/**
	 * 处理选择视图按钮行为
	 *
	 * @param {("toLeft"
	 *       | "toRight"
	 *       | "toAllLeft"
	 *       | "toAllRight")} type
	 * @memberof MPickupView2Controller
	 */
	public handleMPickupViewPickButtonAction(
		type: 'toLeft' | 'toRight' | 'toAllLeft' | 'toAllRight'
	): void {
		this.buttonAction = type;
		switch (type) {
			case 'toLeft':
				this.handleUnSelectItems();
				break;
			case 'toRight':
				this.handleSelectItems();
				break;
			case 'toAllLeft':
				this.handleUnSelectAll();
				break;
			case 'toAllRight':
				this.handleSelectAll();
				break;
		}
	}

	/**
	 * 处理值变更
	 *
	 * @protected
	 * @param {IParam[]} data
	 * @memberof MPickupView2Controller
	 */
	protected handleValueChange(data: IParam[]) {
		const tempData = [...data];
		this.store.selections.forEach((item: IParam) => {
			const index = data.findIndex((i: IParam) => i.srfkey === item.srfkey);
			if (index === -1) {
				tempData.push(item);
			}
		});
		if (this.buttonAction) {
			if (this.buttonAction === 'toAllRight') {
				this.store.selections = [...this.store.selectionCache, ...tempData];
			} else if (this.buttonAction === 'activeSelection') {
				this.store.selectionCache = this.store.selections.filter(
					(select: IParam) => {
						const index = tempData.findIndex((item: IParam) =>
							Object.is(select.srfkey, item.srfkey)
						);
						return index === -1;
					}
				);
			}
		}
		this.store.tempSelections = [...this.store.selectionCache, ...tempData];
		this.buttonAction = '';
		this.store.panelSelectedKeys.length = 0;
	}

	/**
	 * 计算默认选中（外部有值时第一次进入页面计算默认选中）
	 *
	 * @private
	 * @param {IParam[]} data
	 * @return {*}
	 * @memberof MPickupView2Controller
	 */
	private computeDefaultSelect() {
		const { viewParams } = this.store;
		if (
			this.isDefaultSelect &&
			viewParams &&
			viewParams.srfselecteddata &&
			viewParams.srfselecteddata.length !== 0
		) {
			this.store.selections = viewParams.srfselecteddata;
		}
	}

	/**
	 * 处理部件行为
	 *
	 * @param {string} name
	 * @param {string} action
	 * @param {IParam[]} data
	 * @memberof MPickupView2Controller
	 */
	public handleCtrlAction(name: string, action: string, data: IParam[]): void {
		super.handleCtrlAction(name, action, data);
		const treeExpBar = this.getTreeExpCtrlAbility();
		if (treeExpBar && treeExpBar.name === name) {
			this.handleTreeExpCtrlAction(action, data);
		}
	}

	/**
	 * 处理选择视图面板事件
	 *
	 * @param {string} action
	 * @param {IParam[]} data
	 * @memberof MPickupView2Controller
	 */
	public handlePickupViewPanelAction(action: string, data: IParam[]) {
		super.handlePickupViewPanelAction(action, data);
		switch (action) {
			case 'dataLoaded':
				this.handleDataLoaded();
				break;
		}
	}

	/**
	 * 处理树导航部件行为
	 *
	 * @protected
	 * @param {string} action
	 * @param {IParam[]} data
	 * @memberof MPickupView2Controller
	 */
	protected handleTreeExpCtrlAction(action: string, data: IParam[]) {
		switch (action) {
			case 'selectionChange':
				this.handleTreeExpValueChange(data as INavigateParam[]);
				break;
		}
	}

	/**
	 * 处理树导航值变化
	 *
	 * @protected
	 * @param {IParam[]} data
	 * @memberof MPickupView2Controller
	 */
	protected handleTreeExpValueChange(param: INavigateParam[]) {
		if (!param || param.length === 0) {
			return;
		}
		this.store.navParam = param[0];
		Object.assign(this.store.navParam.navData.viewParams, {
			srfselecteddata: this.store.selections,
		});
		if (!this.model.useDefaultLayout) {
			const navPos: any = Object.values(this.store.layoutModelDetails).find(
				(item: any) => {
					return item.predefinedType === 'NAV_POS';
				}
			);
			if (navPos) {
				navPos.setNavData(param[0]);
			}
		}
		const ability = this.getMainCtrlAbility();
		if (ability) {
			nextTick(() => {
				ability.load();
			});
		}
	}

	/**
	 * 处理数据激活
	 *
	 * @protected
	 * @param {IParam[]} data
	 * @memberof MPickupView2Controller
	 */
	protected handleDataActive(data: IParam[]) {
		this.emit('viewDataChange', this.store.selections);
	}

	/**
	 * 处理数据激活
	 *
	 * @protected
	 * @param {IParam[]} data
	 * @memberof PickupViewController
	 */
	protected handleDataLoaded() {
		this.buttonAction = 'activeSelection';
		const ability = this.getMainCtrlAbility();
		if (ability) {
			(ability as IPickupViewPanelAbility).selectItems(this.store.selections);
		}
	}

	/**
	 * 选中数据
	 *
	 * @protected
	 * @memberof MPickupView2Controller
	 */
	protected handleSelectItems() {
		this.store.selections = [...this.store.tempSelections];
		const ability = this.getMainCtrlAbility();
		if (ability) {
			(ability as IPickupViewPanelAbility).selectItems(
				this.store.tempSelections
			);
		}
	}

	/**
	 * 取消选中数据
	 *
	 * @protected
	 * @memberof MPickupView2Controller
	 */
	protected handleUnSelectItems() {
		const ability = this.getMainCtrlAbility();
		if (ability) {
			this.store.selectionCache = this.store.selectionCache.filter(
				(item: IParam) => {
					return this.store.panelSelectedKeys.indexOf(item.srfkey) === -1;
				}
			);
			this.store.selections = this.store.selections.filter((item: IParam) => {
				return this.store.panelSelectedKeys.indexOf(item.srfkey) === -1;
			});
			this.store.tempSelections = this.store.selections;
			(ability as IPickupViewPanelAbility).selectItems(
				this.store.tempSelections
			);
		}
	}

	/**
	 * 选中全部
	 *
	 * @protected
	 * @memberof MPickupView2Controller
	 */
	protected handleSelectAll() {
		const ability = this.getMainCtrlAbility();
		if (ability) {
			(ability as IPickupViewPanelAbility).selectAll();
		}
	}

	/**
	 * 取消选中全部
	 *
	 * @protected
	 * @memberof MPickupView2Controller
	 */
	protected handleUnSelectAll() {
		const ability = this.getMainCtrlAbility();
		if (ability) {
			this.store.selections = [];
			this.store.selectionCache = [];
			(ability as IPickupViewPanelAbility).selectItems([]);
		}
	}

	/**
	 * 处理多数据视图行为
	 *
	 * @param {string} action
	 * @param {IParam} data
	 * @memberof MPickupView2Controller
	 */
	public handleMPickupViewAction(action: string, data: IParam): void {
		if (action === 'panelItemClick') {
			this.pickerItemClick(data);
		}
	}

	/**
	 * 选择项点击
	 *
	 * @param {IParam} item
	 * @memberof MPickupView2Controller
	 */
	private pickerItemClick(item: IParam) {
		const index = this.store.panelSelectedKeys.findIndex(
			(key: string) => key === item.srfkey
		);
		if (index === -1) {
			this.store.panelSelectedKeys.push(item.srfkey);
		} else {
			this.store.panelSelectedKeys.splice(index, 1);
		}
	}
}
